﻿using System;
using System.Threading.Tasks;
using MassTransit.Courier;
using MassTransitDemo.OrderService.Common.Exceptions;
using Microsoft.Extensions.Logging;

namespace MassTransitDemo.OrderService.Handlers
{
    public class CreateOrderActivity : IExecuteActivity<CreateOrderModel>
    {
        private readonly ILogger<CreateOrderActivity> logger;

        public CreateOrderActivity(ILogger<CreateOrderActivity> logger)
        {
            this.logger = logger;
        }

        public async Task<ExecutionResult> Execute(ExecuteContext<CreateOrderModel> context)
        {
            logger.LogInformation($"开始创建订单-{DateTime.Now.ToString("HH:mm:ss")}");
            await Task.Delay(100);

            if (DateTime.Now.Second <= 20)
            {
                logger.LogInformation($"数据库连接超时-创建订单失败-{DateTime.Now.ToString("HH:mm:ss")}");
                throw new CommonActivityExecuteFaildException("数据库连接超时");
            }

            if (DateTime.Now.Second > 20 && DateTime.Now.Second <= 40)
            {
                logger.LogInformation($"当日订单已达到上限-创建订单失败-{DateTime.Now.ToString("HH:mm:ss")}");
                return context.FaultedWithVariables(new Exception("当日订单已达到上限"), new CreateOrderResult { OrderId = "111122", Message = "订单上限" });
            }

            logger.LogInformation($"创建订单成功-{DateTime.Now.ToString("HH:mm:ss")}");
            return context.CompletedWithVariables(new CreateOrderResult { OrderId = "111122", Message = "创建订单成功" });
        }
    }

    public class CreateOrderModel
    {
        public string ProductId { get; set; }
        public string CustomerId { get; set; }
        public int Price { get; set; }
    }

    public class CreateOrderResult
    {
        public string OrderId { get; set; }
        public string Message { get; set; }
    }
}
